package com.fingard.dsp.bank.directbank.zjdsf01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsAPI;
import com.fingard.dsp.bank.directbank.zjdsf01.util.WMACREQ;
import com.fingard.dsp.bank.directbank.zjdsf01.util.Yhtsrdll;
import com.fingard.io.FileHelper;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.util.sm2.SM3Digest;

import java.io.File;
import java.util.Date;
import java.util.Map;

/**
 * 浙江人行E户通(ZJDSF01)基础方法
 */
public class ZJDSF01Base extends DirectBase implements ITcpClient{
	private static TransIDHelper idHelper = new TransIDHelper(1, 9999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

	/**
	 * 获取字符集
	 *
	 * @param p_for
	 * @return
	 */
	protected String getCharset(String p_for){
		return getBankConfig().getCharset("UTF-8", p_for);
	}

	/**
	 * 发送银行
	 *
	 * @param tmpFilePath
	 * @param transCode
	 * @return
	 * @throws Exception
	 */
	protected String[] sendBatchToBank(String tmpFilePath, String transCode) throws Exception {
		String[] tmpStrRet = new String[]{"",""};
		if (StringHelper.isNullOrEmpty(bankFront.loginFlag)) {
			// 登录
			StringBuilder sbFileContent = new StringBuilder();
			
			/** 报文类型 */
			sbFileContent.append(ZJDSF01TransCode.BatRec_Login);
			
			/** 服务类型 */
			sbFileContent.append("01");
			
			/** 发起方代码 */
			sbFileContent.append(String.format("%-10s", bankFront.corpNo));
			
			/** 接收方代码 */
			sbFileContent.append(String.format("%-10s", bankFront.org));
			
			/** 本地日期 */
			sbFileContent.append(Format.Date8Format.format(new Date()));
			
			/** 本地时间 */
			sbFileContent.append(Format.Time6Format.format(new Date()));
			
			/** 回应码 */
			sbFileContent.append("99");
			
			/** 操作员代码 */
			sbFileContent.append(String.format("%-8s", bankFront.operator));  
			
			StringBuilder loginBuilder = new StringBuilder();
			/** 签到方代码 */ 
			loginBuilder.append(CfbsAPI.rightFill(bankFront.corpNo, 10, " "));
			
			/** 签到日期 */
			loginBuilder.append(Format.Date8Format.format(new Date()));
			
			/** 签到时间 */
			loginBuilder.append(Format.Time6Format.format(new Date()));
			
			/** 应答码 */
			loginBuilder.append("99");
			
			/** 签到员代码 */
			loginBuilder.append(CfbsAPI.rightFill(bankFront.operator, 8, " "));
			
			/** 签到类型 */
			loginBuilder.append("1");
			sbFileContent.append(loginBuilder.toString());
			
			WriteBankLogLn("签到报文mac生成请求数据:" + loginBuilder.toString());
			/** 消息鉴别码 */ 
			String tmpEncryptResult = WMACREQ.generateMac(loginBuilder.toString(), getCharset("batch"));
			WriteBankLogLn("当前签到mac:" + tmpEncryptResult);
			
			sbFileContent.append(CfbsAPI.rightFill(tmpEncryptResult, 8, " "));
			
			String tmpLocalMarkPath = getTempFileDirectory() + File.separator + "GMT031.z01";
			WriteBankLogLn2("签到请求文件保存本机路径: " + tmpLocalMarkPath);
			FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset("batch"));
			
			WriteBankLogLn2("服务地址:[" + "ip:" + bankFront.serverIP + ",port:" + bankFront.serverPort + "].");
			String tmpDownDir = getTempFileDirectory();
			WriteBankLogLn2("签到文件银行响应结果文件本机保存目录:" + tmpDownDir);
			
			Map<String, String> tmpMapRet = Yhtsrdll.recvYHTBWFile(bankFront.serverIP, bankFront.serverPort, tmpDownDir, tmpLocalMarkPath);
			
			String tmpRespCode = tmpMapRet.get("code");
			String tmpResultFilePath = tmpMapRet.get("rcvedFName");
			WriteBankLogLn("code:" + tmpMapRet.get("code"));
			WriteBankLogLn("rcvedFName:" + tmpMapRet.get("rcvedFName"));
			
			if ("0".equals(tmpRespCode)) {
				String tmpFileContent = FileHelper.readFileText(tmpResultFilePath, getCharset("batch"));
				WriteBankLogLn2("签到响应报文数据:\r\n" + tmpFileContent);
				String tmpRetCode = tmpFileContent.substring(76, 78);
				if ("00".equals(tmpRetCode)) {
					WriteBankLogLn("签到成功...");
					bankFront.loginFlag = "success";
				} else {
					WriteBankLogLn("签到失败,错误码:" + tmpRetCode);
					tmpStrRet[0] = "-1";
					tmpStrRet[1] = tmpRetCode;
					return tmpStrRet;
				}
			} else {
				tmpStrRet[0] = "-1";
				tmpStrRet[1] = tmpRespCode;
				return tmpStrRet;
			}
		}
		
		WriteBankLogLn2("服务地址:[" + "ip:" + bankFront.serverIP + ",port:" + bankFront.serverPort + "].");
		String tmpDownDir = getTempFileDirectory();
		
		if (ZJDSF01TransCode.BatRec_9188_918801.equals(transCode)) {
			int flag = Yhtsrdll.sendYHTBWFile(bankFront.serverIP, bankFront.serverPort, tmpDownDir, tmpFilePath);
			WriteBankLogLn("发送请求通讯响应码:" + flag);
			if (flag != 0) {
				WriteBankLogLn("发送请求失败,错误码:" + flag);
				tmpStrRet[0] = "-1";
				tmpStrRet[1] = String.valueOf(flag);
			}
		} else {
			Map<String, String> tmpMapRet = Yhtsrdll.recvYHTBWFile(bankFront.serverIP, bankFront.serverPort, tmpDownDir, tmpFilePath);
			String tmpRespCode = tmpMapRet.get("code");
			String tmpResultFilePath = tmpMapRet.get("rcvedFName");
			WriteBankLogLn("code:" + tmpMapRet.get("code"));
			WriteBankLogLn("rcvedFName:" + tmpMapRet.get("rcvedFName"));
			
			if ("0".equals(tmpRespCode)) {
				String tmpFileContent = FileHelper.readFileText(tmpResultFilePath, getCharset("batch"));
				WriteBankLogLn2("批量代扣查询响应报文数据:\r\n" + tmpFileContent);
				tmpStrRet[1] = tmpFileContent;
			} else {
				tmpStrRet[0] = "-1";
				tmpStrRet[1] = tmpRespCode;
			}
		}
		return tmpStrRet;
	}

	/**
	 * 单笔交易发送银行
	 *
	 * @param tmpJsonSign
	 * @param transCode
	 * @return
	 * @throws Exception
	 */
	protected String[] sendRealTimeToBank(JSONObject tmpJsonSign, String transCode) throws Exception {
        String[] tmpStrRet = new String[]{"", ""};

        String tmpSignData = JSON.toJSONString(tmpJsonSign);
		WriteBankLogLn2("签名原始数据:\r\n" + tmpSignData);
		
		String signature = SM3Digest.sM3Sign(tmpSignData);
		WriteBankLogLn2("签名结果:" + signature);
		
		StringBuilder tmpReqHeader = new StringBuilder();
		tmpReqHeader.append(transCode);
		tmpReqHeader.append(String.format("%-10s", bankFront.corpNo)); 
		tmpReqHeader.append(String.format("%-10s", bankFront.org));
		tmpReqHeader.append(getQryTransID());
		tmpReqHeader.append(Format.DateTime14Format.format(new Date()));
		tmpReqHeader.append("J");
		tmpReqHeader.append(signature);
		tmpReqHeader.append(tmpSignData);
		
		int tmpMsgLen = tmpReqHeader.toString().getBytes(getCharset("realtime")).length;
		String tmpReqData = String.format("%04d", tmpMsgLen) + tmpReqHeader.toString();
		WriteBankLogStep2(tmpReqData);
		
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + bankFront.serverPort + "]。");

        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpReqData.getBytes(getCharset("realtime")));
        tmpStrRet[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            tmpStrRet[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset("realtime"));
        } else {
            tmpStrRet[1] = tmpReceiver.getConnMsg();
        }
        WriteBankLogStep3(tmpStrRet[1]);
        if (tmpStrRet[1].contains("{")) {
        	tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("{"));
        }
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }

        return tmpStrRet;
    }

    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 4) {
                p_receiver.contentLength = Integer.parseInt(new String(p_receiver.recBytes, 0, 4, getCharset("realtime"))) + 4;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}